import json
import requests
import datetime
from datetime import datetime


def save_json(fp, data, out_file=True, class_type=None):
    """
    保存json文件
    :param fp:
    :param data:
    :param out_file
    :param class_type
    :return:
    """
    if out_file and len(data) > 0:
        with open(fp, 'a+', encoding="utf-8") as w:
            if class_type is None:
                w.write(json.dumps(data, indent=4, ensure_ascii=False))
            else:
                w.write(json.dumps(data, indent=4, ensure_ascii=False, cls=class_type))


def read_json(fp):
    """
    读取json文件
    :param fp:
    :return:
    """
    with open(fp, 'r', encoding="utf-8") as r:
        return json.loads(r.read())


def get_json(url: str):
    """
    get函数，返回json数据
    :param url:
    :return:
    """
    with requests.get(url)as resp:
        if resp.status_code == 200:
            return resp.json()
    return {}


def post_json(url: str, dp=None, jp=None):
    """
    post函数，返回json数据
    :param url:
    :param dp:data:
    :param jp:json_para:
    :return:
    """
    with requests.post(url, data=dp, json=jp)as resp:
        if resp.status_code == 200:
            return resp.json()
    return {}


def save_text(fp: str, text: str):
    """
    保存文本文件
    :param fp:
    :param text:
    :return:
    """
    with open(fp, "a+", encoding="utf-8")as w:
        w.write(text)


def date_grouping(dates, split_index=7):
    """
    日期分组
    :param dates:
    :param split_index
    :return:
    """
    if len(dates) > 1:
        result = {date[:split_index]: [] for date in dates}
        for date in dates:
            result[date[:split_index]].append(date)
        return list(result.values())
    return [dates]


def dates_timestamp(dates: list, fmt="%Y-%m-%d"):
    return int(datetime.strptime(dates[0], fmt).timestamp()), int(datetime.strptime(dates[-1], fmt).timestamp())


class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime("%Y-%m-%d %H:%M")
        else:
            return json.JSONEncoder.default(self, obj)


class TimeEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.time):
            return obj.strftime("%Y-%m-%d %H:%M:%S")
        else:
            return json.JSONEncoder.default(self, obj)
